import os

from ..lda import get_lda_model


def convert_gensim_lda2familia(model_fp):
    gensim_lda = get_lda_model(model_fp)
    model_dir = os.path.dirname(model_fp)
    model_name = os.path.basename(model_fp)
    print('Output vocab..')
    with open('%s/vocab_info.txt' % model_dir, 'w', encoding='utf-8') as fo:
        for wid, token in gensim_lda.id2word.items():
            row = ['word', token, '%d' % wid, 'null', 'null']
            fo.write('\t'.join(row) + '\n')
    print('Output term-topic matrix..')
    counter, vocab_size = 0, len(gensim_lda.id2word.keys())
    with open('%s.nw' % model_fp, 'w', encoding='utf-8') as fo:
        for wid in range(vocab_size):
            counter += 1
            row = ['%d' % wid]
            for tid in range(gensim_lda.num_topics):
                value = gensim_lda.state.sstats[tid][wid]
                if value > 1:
                    row.append('%d:%d' % (tid, value))
            fo.write(' '.join(row) + '\n')
            print('\r%d/%d..' % (counter, vocab_size), end='')
    print('Output model configure..')
    with open('%s.conf' % model_fp, 'w', encoding='utf-8') as fo:
        conf = """type: LDA
num_topics: %d
alpha: %f
beta: %f
word_topic_file: "%s.nw"
vocab_file: "vocab_info.txt"
""" % (gensim_lda.num_topics, gensim_lda.alpha[0], gensim_lda.eta[0], model_name)
        fo.write(conf)
